const tree = [
  {
    title: '0-0',
    key: '0-0',
    children: [
      {
        title: '0-0-0',
        key: '0-0-0',
        children: [{ title: '0-0-0-0', key: '0-0-0-0' }]
      },
      {
        title: '0-0-1',
        key: '0-0-1'
      }
    ]
  }
]
/**
 * 扁平化树结构
 * @param {*} tree 树结构数据
 * @param {*} pid 父级id 、顶层节点默认无
 * @param {*} children 子节点属性key值，默认为children
 * @param {*} id 节点属性key值，默认为id
 * @returns
 */

const toFlatArray = (tree, pid, children = 'children', id = 'key') => {
  return tree.reduce((t, _) => {
    const child = _[children] // 是否含有子节点
    return [
      ...t, // 初始值
      pid ? { ..._, pid } : _, // 子节点增加 pid
      // 将子节点全部解构实现扁平化
      ...(child && child.length ? toFlatArray(child, _[id]) : [])
    ]
  }, [])
}
const result = toFlatArray(tree)
console.log(result)
